package com.topwalk.service;
 
import lombok.extern.slf4j.Slf4j;
 
import java.util.concurrent.TimeUnit;
 
/**
 * 测试两阶段终止
 * 
 * @Author LeoLee
 * @Date 2020/11/29
 * @Version V1.0
 **/
@Slf4j
public class ThreadStatusTest {
 
    
    @Slf4j
    static
    class TwoPhaseTermination {
 
        private Thread monitor;
 
        //启动监控线程
        public void start() {
            monitor = new Thread(() -> {
                //模拟线程在运行当中
                for (;;) {
                    Thread monitor = Thread.currentThread();
                    if (monitor.isInterrupted()) {
                        log.info("{}被打断，执行被打断的之后的处理......", monitor.getName());
                        break;
                    } else {
                        try {
                            Thread.sleep(1000);
                            log.info("{}运行正常，执行业务处理......", monitor.getName());
                        } catch (InterruptedException e) {
                            //如果在sleep的时候被打断了，要重置线程的打断状态为true，如果没有这一步，会打断失败，因为sleep wait join会将打断状态设置为false
                            monitor.interrupt();
                            e.printStackTrace();
                        }
                    }
                }
            }, "monitor");
 
            monitor.start();
        }
 
        //停止监控线程
        public void stop() {
            monitor.interrupt();
        }
 
    }
 
 
    public static void main(String[] args) throws InterruptedException {
 
        //两阶段终止模式
        TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
        twoPhaseTermination.start();
        Thread.sleep(3*1000);
        twoPhaseTermination.stop();
    }
    
}